package com.qhy.wxpay.controller.pay;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.qhy.wxpay.common.QhyStaticParameter;
import com.qhy.wxpay.entity.VipSettings;
import com.qhy.wxpay.service.VipSettingsService;
import com.qhy.wxpay.utils.HttpUtils;
import com.qhy.wxpay.utils.WeixinchatPayUtils;
import com.qhy.wxpay.vo.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RequestMapping("/app")
public class WechatJSAPIController {
    Logger log = LoggerFactory.getLogger(WechatJSAPIController.class);

    @Autowired
    private VipSettingsService vipSettingsService;

    /**
     * 付款订单Api,根据传入的订单号 生成付款二维码
     * 参考网址：https://pay.weixin.qq.com/wiki/doc/apiv3/open/pay/chapter2_8_2.shtml
     */
    @RequestMapping("/weixinpay")
    public R jsapiweixinpay(String openid, Integer pid) throws JsonProcessingException {
        log.info("支付的产品是:{}", pid);
        VipSettings vipSettings = vipSettingsService.getById(pid);
        if (vipSettings == null) return R.error();
        //封装请求参数
        Map<String, Object> map = new HashMap();
        // 支付的产品（小程序或者公众号，主要需要和微信支付绑定哦）
        map.put("appid", QhyStaticParameter.appId);
        // 支付的商户号
        map.put("mchid", QhyStaticParameter.mchId);
        //临时写死配置
        map.put("description", vipSettings.getName());
        map.put("out_trade_no", String.valueOf(System.currentTimeMillis()));
        map.put("notify_url", QhyStaticParameter.notifyUrl);

        Map<String, Object> amount = new HashMap();
        //订单金额 单位分
        amount.put("total", Integer.parseInt(getMoney(vipSettings.getTprice())));
        amount.put("currency", "CNY");
        map.put("amount", amount);
        // 设置小程序所需的opendi
        Map<String, Object> payermap = new HashMap();
        payermap.put("openid", openid);
        map.put("payer", payermap);

        ObjectMapper objectMapper = new ObjectMapper();
        String body = objectMapper.writeValueAsString(map);
        log.info("支付的相关参数是：{}", body);

        Map<String, Object> stringObjectMap = HttpUtils.doPostWexin(QhyStaticParameter.unifiedOrderUrlJS, body);
        //通过prepay_id获取签名信息
        try {
            HashMap<String, Object> dataMap = WeixinchatPayUtils.getTokenWeixin(QhyStaticParameter.appId, String.valueOf(stringObjectMap.get("prepay_id")));
            return R.ok().data("dataMap", dataMap);
        } catch (Exception ex) {
            return R.error().code(1001).message("出错了!!!");
        }
    }


    /**
     * 元转换成分
     *
     * @param money
     * @return
     */
    private String getMoney(String money) {
        if (money == null || money.equalsIgnoreCase("0")) {
            return "";
        }
        // 金额转化为分为单位
        // 处理包含, ￥ 或者$的金额
        String currency = money.replaceAll("\\$|\\￥|\\,", "");
        int index = currency.indexOf(".");
        int length = currency.length();
        Long amLong = 0l;
        if (index == -1) {
            amLong = Long.valueOf(currency + "00");
        } else if (length - index >= 3) {
            amLong = Long.valueOf((currency.substring(0, index + 3)).replace(".", ""));
        } else if (length - index == 2) {
            amLong = Long.valueOf((currency.substring(0, index + 2)).replace(".", "") + 0);
        } else {
            amLong = Long.valueOf((currency.substring(0, index + 1)).replace(".", "") + "00");
        }
        return amLong.toString();
    }

}
